package com.xxq.gulimall.product.exception;


/*集中处理所有异常*/

import com.xxq.common.exception.BizCodeEnum;
import com.xxq.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Slf4j // 日志记录
@RestControllerAdvice(basePackages = "com.xxq.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    // 指定处理数据校验异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型{}", e.getMessage(), e.getClass());

        // param1：异常字段，param2：异常消息
        HashMap<String, String> errorMap = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(fieldError -> { // 获取所有异常
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });

        return R.error(BizCodeEnum.VALID_EXCEPTION).put("data", errorMap);
    }

    // 捕获所有异常
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        String data = "异常描述：" + throwable.getMessage()
                + "，异常类型：" + throwable.getMessage();
        log.error("异常描述：{}，异常类型：{}", throwable.getMessage(), throwable.getClass());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION).put("data", throwable);
    }
}
